using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    /// <summary>
    /// Shift right logical
    /// </summary>
    public class Srl : Instruction
    {
        public override void Set(uint address, uint value)
        {
            base.Set(address, value);

            if (ImmediateValue != 0x41)
                throw new UnknownInstructionException(value);
        }

        public override int CycleCount
        {
            get { return 1; }
        }

        public Srl()
            : base("srl")
        {
        }

        /// <summary>
        /// Shifts logically the contents of register rA, one bit to the right, 
        /// and places the result in rD. A zero is shifted in the shift chain 
        /// and placed in the most significant bit of rD. The least significant 
        /// bit coming out of the shift chain is placed in the Carry flag.
        /// </summary>    
        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            uint ra = MicroblazeComponent.ReadRegister(SourceRegisterA);
            uint value = (ra >> 1);
            value &= 0x7FFFFFFF;
            MicroblazeComponent.WriteRegister(DestinationRegister, value, Address);

            if ((ra & 1) == 1)
                MicroblazeComponent.ArithmeticCarry = true;
            else
                MicroblazeComponent.ArithmeticCarry = false;
        }

        public override string ToString()
        {
            return string.Format("srl r{0}, r{1}",
              DestinationRegister,
              SourceRegisterA
            );
        }
    }
}
